import Info from "./info";
import Stats from "./stats";
import Record from "./record";
import Realog from "./realog";
import Config from "./config";
import Histlog from "./histlog";
import NoFoundPage from "@/pages/404";
import Editor from "@/pages/hosting/appMorePage/Editor";
import { useNavigate } from "react-router-dom";
import React, { useState, useEffect } from "react";
import type { APP } from "@/pages/hosting/typings";
import { postAppRemove } from "@/services/hosting/api";
import { Deploy } from "@/pages/hosting/manager/deploy";
import { motion, AnimatePresence } from "framer-motion";
import { postAppInfo, postAppControl } from "@/services/hosting/api";
import {
    LeftOutlined,
    CopyOutlined,
    CloudUploadOutlined,
} from "@ant-design/icons";
import {
    Layout,
    Avatar,
    Divider,
    Button,
    Tooltip,
    Space,
    message,
    Segmented,
    theme,
    Spin,
    Modal,
} from "antd";

const AppMorePage: React.FC = () => {
    const [show404, setShow404] = useState(false);
    const { Header, Content } = Layout;
    const { useToken } = theme;
    const navigate = useNavigate();
    const params = new URLSearchParams(location.search);
    const appId: string = params.get("appId") || "";
    const stype: string = params.get("type") || "";
    if (!["java", "Java", "Static", "static"].includes(stype)) {
        return <NoFoundPage title={"不支持的类型！"} />;
    }
    const [current, setCurrent] = useState<string>("info");
    const [direction, setDirection] = useState(0);
    const { token } = useToken();
    const [app, setApp] = useState<APP | null>(null);
    const [appInfo, setAppInfo] = useState();
    const [loading, setLoading] = useState(true);
    const [showDeploy, setShowDeploy] = useState(false);
    const [isDeployVisible, setIsDeployVisible] = useState(false);
    const [isDeployMounted, setIsDeployMounted] = useState(false);
    
    // 从URL中获取nodeId
    const getUrlNodeId = () => {
        return params.get('nodeId') || '0';
    };
    
    const [nodeId, setNodeId] = useState(getUrlNodeId());

    // 监听URL变化
    useEffect(() => {
        const newNodeId = getUrlNodeId();
        setNodeId(newNodeId);
    }, [location.search]);

    const handleCopy = () => {
        if (app) {
            navigator.clipboard.writeText(app.app_id);
            message.info("复制成功");
        }
    };
    const translateStype = (stype: string): string => {
        const lowerStype = stype.toLowerCase();
        switch (lowerStype) {
            case "java" || "Java":
                return "Java服务";
            case "static" || "Static":
                return "前端静态文件";
            default:
                return stype;
        }
    };
    if (!["java", "static", "Java", "Static"].includes(stype)) {
        message.error("类型错误！");
        history.back();
    }
    const autoRefresh = async () => {
        const res = await postAppInfo({ app_id: appId }, stype, nodeId, navigate);
        if (res.status === "success") {
            setApp(res.message.now_data);
            setAppInfo(res.message as any)
        }
    };
    useEffect(() => {
        const intervalId = setInterval(() => {
            autoRefresh();
        }, 5000);
        // 组件卸载时清除定时器
        return () => {
            clearInterval(intervalId);
        };
    }, []);
    const AppControlButton = ({
        status,
        onStart,
        onStop,
        loading = false,
    }: {
        status?: string;
        onStart: () => void;
        onStop: () => void;
        loading?: boolean;
    }) => {
        const { token } = theme.useToken();
        const isRunning =
            status?.toLowerCase() === "running" ||
            status?.toLowerCase() === "mapping";

        const getButtonProps = () => {
            const baseStyle = {
                width: 48,
                height: 48,
                padding: 0,
                border: "none",
                borderRadius: "50%",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                transition: "all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1)",
                boxShadow: "0 2px 0 rgba(0, 0, 0, 0.02)",
                "&:hover": {
                    transform: "scale(1.1)",
                },
                "&:active": {
                    transform: "scale(0.95)",
                },
            };

            if (isRunning) {
                return {
                    ...baseStyle,
                    backgroundColor: token.colorPrimary,
                    color: "white",
                    boxShadow: `0 2px 4px ${token.colorPrimaryBg}`,
                    cursor: "pointer",
                    icon: (
                        <div
                            style={{
                                width: 16,
                                height: 16,
                                backgroundColor: "white",
                                borderRadius: 2,
                                transition: "all 0.3s",
                            }}
                        />
                    ),
                    onClick: onStop,
                    tooltip: "停止",
                };
            } else {
                return {
                    ...baseStyle,
                    backgroundColor: "#f5f5f5",
                    color: token.colorTextSecondary,
                    boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
                    cursor: "pointer",
                    icon: (
                        <div
                            style={{
                                width: 0,
                                height: 0,
                                borderTop: "8px solid transparent",
                                borderBottom: "8px solid transparent",
                                borderLeft: `12px solid ${token.colorTextSecondary}`,
                                transition: "all 0.3s",
                            }}
                        />
                    ),
                    onClick: onStart,
                    tooltip: "启动",
                };
            }
        };

        const buttonProps = getButtonProps();

        return (
            <Tooltip title={buttonProps.tooltip}>
                <Button
                    size="large"
                    style={{
                        ...buttonProps,
                        display: "flex",
                        justifyContent: "center",
                        alignItems: "center",
                    }}
                    icon={buttonProps.icon}
                    onClick={buttonProps.onClick}
                    disabled={loading}
                    loading={loading}
                />
            </Tooltip>
        );
    };
    const initAppInfo = async () => {
        setLoading(true);
        setIsDeployMounted(false);
        setIsDeployVisible(false);
        try {
            const res = await postAppInfo({ app_id: appId }, stype, nodeId, navigate);
            if (res.status === "success") {
                setApp(res.message.now_data);
                setAppInfo(res.message as any)
                setLoading(false);
            } else if (res.status === "error") {
                console.log("渲染404");
                setShow404(true);
                setLoading(false);
            }
        } catch (err) {
            message.error("应用获取失败！");
            console.log("应用数据获取失败：", err);
            history.back();
        }
    };

    useEffect(() => {
        initAppInfo();
        return () => { };
    }, []);

    let options: any = [];
    if (["Java", "java"].includes(stype)) {
        options = [
            { label: "详情", value: "info" },
            { label: "编辑", value: "editor" },
            { label: "实时日志", value: "realog" },
            { label: "发布记录", value: "record" },
        ];
    } else if (["Static", "static"].includes(stype)) {
        options = [
            { label: "详情", value: "info" },
            { label: "编辑", value: "editor" },
            { label: "发布记录", value: "record" },
        ];
    }

    const onChange = (value: string) => {
        if (loading) return; // 加载中不允许切换
        const currentIndex = options.findIndex(
            (item: any) => item.value === current,
        );
        const nextIndex = options.findIndex((item: any) => item.value === value);
        setDirection(nextIndex > currentIndex ? 1 : -1);
        setCurrent(value);
    };

    const renderContent = () => {
        switch (current) {
            case "info":
                return (
                    <div style={{ margin: "auto auto", width: "95%" }}>
                        <Info {...app} />
                    </div>
                );
            case "editor":
                return (
                    <div
                        style={{
                            height: "calc(86vh - 210px)",
                            display: "flex",
                            flexDirection: "column",
                            overflow: "hidden",
                        }}
                    >
                        <Editor />
                    </div>
                );
            case "config":
                return (
                    <div>
                        <Config />
                    </div>
                );
            case "record":
                return (
                    <div>
                        <Record onRollbackSuccess={initAppInfo} />
                    </div>
                );
            case "realog":
                return (
                    <div
                        style={{
                            height: "calc(86vh - 210px)",
                            display: "flex",
                            flexDirection: "column",
                            overflow: "hidden",
                        }}
                    >
                        <Realog />
                    </div>
                );
            case "histlog":
                return (
                    <div
                        style={{
                            height: "calc(86vh - 210px)",
                            display: "flex",
                            flexDirection: "column",
                            overflow: "hidden",
                        }}
                    >
                        <Histlog />
                    </div>
                );
            case "stats":
                return (
                    <div>
                        <Stats />
                    </div>
                );
            default:
                return <div>请选择菜单项</div>;
        }
    };

    const variants = {
        enter: (direction: number) => ({
            x: direction > 0 ? "100%" : "-100%",
            opacity: 0,
        }),
        center: {
            x: 0,
            opacity: 1,
        },
        exit: (direction: number) => ({
            x: direction > 0 ? "-100%" : "100%",
            opacity: 0,
        }),
    };

    const getStatusColor = (status?: string) => {
        switch (status?.toLowerCase()) {
            case "running":
                return "#52c41a"; // 运行中-绿色
            case "dead":
                return "#faad14"; // 已停止-橙色
            case "error":
                return "#f5222d"; // 错误-红色
            case "mapping":
                return "#52c41a"; // 已启用-绿色
            case "unmapped":
                return "#faad14"; // 未启用-橙色
            default:
                return token.colorTextSecondary; // 默认颜色
        }
    };

    const getStatusText = (status?: string) => {
        switch (status?.toLowerCase()) {
            case "running":
                return "运行中";
            case "dead":
                return "已停止";
            case "error":
                return "异常";
            case "mapping":
                return "已启用";
            case "unmapped":
                return "未启用";
            default:
                return "未知状态";
        }
    };

    const requestControl = async (behavior: string) => {
        let behaviorList = [];
        if (["Java", "java"].includes(stype)) {
            behaviorList = ["start", "stop", "restart"];
        } else if (["Static", "static"].includes(stype)) {
            behaviorList = ["enable", "disable"];
        } else {
            message.error("无效的操作");
            return;
        }
        if (behaviorList.includes(behavior)) {
            await postAppControl(
                { app_id: appId, behavior: behavior },
                stype,
                nodeId, 
                navigate,
            )
                .then(async (res: any) => {
                    message.info(res.message);
                    await initAppInfo();
                })
                .catch((err: any) => {
                    message.error(err.respone.data.message);
                });
        }
    };

    const handleStart = async () => {
        message.info("启动中，稍后会自动刷新...");
        if (["Java", "java"].includes(stype)) {
            await requestControl("start");
        } else if (["Static", "static"].includes(stype)) {
            await requestControl("enable");
        } else {
            message.error("无效的操作");
        }
    };

    const handleStop = async () => {
        message.info("停止中，稍后会自动刷新...");
        if (["Java", "java"].includes(stype)) {
            await requestControl("stop");
        } else if (["Static", "static"].includes(stype)) {
            await requestControl("disable");
        } else {
            message.error("无效的操作");
        }
    };

    const handleDeployClick = () => {
        setShowDeploy(true);
        setIsDeployMounted(true);
        setTimeout(() => setIsDeployVisible(true), 10);
    };

    const handleDeployClose = () => {
        setIsDeployVisible(false);
        setTimeout(() => {
            setIsDeployMounted(false);
            setShowDeploy(false);
        }, 300);
    };

    const removeButton = async () => {
        Modal.confirm({
            title: "确认删除",
            content: "确认删除该应用吗？",
            okText: "确认",
            okType: "danger",
            onOk: async () => {
                message.info("删除中，稍后会自动刷新...");
                await postAppRemove(appId, stype, nodeId, navigate).then(
                    async (res) => {
                        message.info(res.message);
                        navigate("/hosting");
                    },
                );
            },
            onCancel: () => {
                message.info("已取消删除");
            },
        });
    };

    if (loading) {
        return (
            <div
                style={{
                    height: "86vh",
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    backgroundColor: "#fff",
                }}
            >
                <Spin size="large" tip="加载中..." />
            </div>
        );
    }
    if (show404) {
        return <NoFoundPage title={"应用不存在！"} />;
    }

    return (
        <div
            style={{
                height: "86vh",
                display: "flex",
                flexDirection: "column",
                overflow: "hidden",
                userSelect: "none",
            }}
        >
            <Layout
                style={{
                    borderRadius: 8,
                    overflow: "hidden",
                    height: "100%",
                    display: "flex",
                    flexDirection: "column",
                }}
            >
                <Header
                    style={{
                        color: "#fff",
                        height: "12vh",
                        minHeight: "80px",
                        backgroundColor: "#fff",
                        padding: "0 20px",
                        display: "flex",
                        alignItems: "center",
                        flexShrink: 0,
                        justifyContent: "space-between",
                    }}
                >
                    <Space
                        size="middle"
                        style={{ display: "flex", alignItems: "center" }}
                    >
                        <Tooltip title="返回">
                            <Button
                                shape="circle"
                                type="text"
                                icon={<LeftOutlined style={{ fontSize: 18 }} />}
                                onClick={() => window.history.back()}
                                style={{ marginRight: 10 }}
                            />
                        </Tooltip>

                        <Avatar
                            size={80}
                            style={{
                                backgroundColor: "transparent",
                                display: "flex",
                                justifyContent: "center",
                                alignItems: "center",
                            }}
                            icon={
                                <img
                                    src={`/icons/${stype.toLowerCase()}.svg`}
                                    alt={stype}
                                    style={{
                                        width: 60,
                                        height: 60,
                                        objectFit: "contain",
                                    }}
                                />
                            }
                        />

                        <div
                            style={{
                                marginLeft: 20,
                                display: "flex",
                                flexDirection: "column",
                                justifyContent: "center",
                                height: "100%",
                                padding: "12px 0",
                            }}
                        >
                            <h2
                                style={{
                                    margin: 0,
                                    color: "#000",
                                    fontSize: 24,
                                    fontWeight: 600,
                                    lineHeight: 1.2,
                                    marginBottom: 4,
                                    userSelect: "text",
                                }}
                            >
                                {app?.alias || "未命名应用"}
                            </h2>
                            <Space
                                size={4}
                                align="center"
                                style={{
                                    padding: 0,
                                    margin: 0,
                                    height: 20,
                                    display: "flex",
                                    alignItems: "center",
                                }}
                            >
                                <span
                                    style={{
                                        color: "rgba(0, 0, 0, 0.45)",
                                        fontSize: 14,
                                        userSelect: "text",
                                    }}
                                >
                                    ID: {app?.app_id || "N/A"}
                                </span>
                                <Tooltip title="复制ID">
                                    <Button
                                        type="text"
                                        size="small"
                                        icon={
                                            <CopyOutlined
                                                style={{ fontSize: 12 }}
                                            />
                                        }
                                        onClick={handleCopy}
                                        style={{
                                            padding: 0,
                                            width: 16,
                                            height: 16,
                                            marginLeft: 4,
                                        }}
                                    />
                                </Tooltip>
                                <span
                                    style={{
                                        color: "rgba(0, 0, 0, 0.45)",
                                        fontSize: 14,
                                    }}
                                >
                                    | 类型: {translateStype(stype)}
                                </span>
                            </Space>
                        </div>
                    </Space>
                    <Space size={8} align="center">
                        <div style={{ marginRight: 16, textAlign: "right" }}>
                            <div
                                style={{
                                    fontWeight: 600,
                                    fontSize: 14,
                                    color: token.colorText,
                                    lineHeight: "22px",
                                }}
                            >
                                运行状态
                            </div>
                            <div
                                style={{
                                    fontSize: 12,
                                    color: getStatusColor(app?.status),
                                    lineHeight: "20px",
                                }}
                            >
                                {getStatusText(app?.status)}
                            </div>
                        </div>

                        <AppControlButton
                            status={app?.status}
                            onStart={handleStart}
                            onStop={handleStop}
                            loading={loading}
                        />

                        <Tooltip title="发布">
                            <Button
                                shape="circle"
                                size="large"
                                style={{
                                    width: 48,
                                    height: 48,
                                    padding: 0,
                                    backgroundColor: token.colorPrimary,
                                    color: "white",
                                    border: "none",
                                    boxShadow: `0 2px 4px ${token.colorPrimaryBg}`,
                                    cursor: "pointer",
                                    transition: "all 0.3s",
                                    // @ts-ignore
                                    ":hover": {
                                        backgroundColor:
                                            token.colorPrimaryHover,
                                        transform: "scale(1.1)",
                                        boxShadow: `0 4px 8px ${token.colorPrimaryBg}`,
                                    },
                                }}
                                icon={
                                    <CloudUploadOutlined
                                        style={{
                                            fontSize: 16,
                                            color: "white",
                                            transition: "all 0.3s",
                                        }}
                                    />
                                }
                                onClick={handleDeployClick}
                            />
                        </Tooltip>
                        <Tooltip title="删除">
                            <Button
                                shape="circle"
                                size="large"
                                style={{
                                    width: 48,
                                    height: 48,
                                    padding: 0,
                                    backgroundColor: "#ff4d4f",
                                    color: "white",
                                    border: "none",
                                    boxShadow:
                                        "0 2px 4px rgba(255, 77, 79, 0.3)",
                                    cursor: "pointer",
                                    transition: "all 0.3s",
                                    // @ts-ignore
                                    "&:hover": {
                                        backgroundColor: "#ff7875",
                                        transform: "scale(1.1)",
                                        boxShadow:
                                            "0 4px 8px rgba(255, 77, 79, 0.3)",
                                    },
                                }}
                                icon={
                                    <svg
                                        width="16"
                                        height="16"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        strokeWidth="2"
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                        style={{
                                            color: "white",
                                            transition: "all 0.3s",
                                        }}
                                    >
                                        <polyline points="3 6 5 6 21 6" />
                                        <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
                                        <line x1="10" y1="11" x2="10" y2="17" />
                                        <line x1="14" y1="11" x2="14" y2="17" />
                                    </svg>
                                }
                                onClick={removeButton}
                            />
                        </Tooltip>
                    </Space>
                </Header>

                <Divider style={{ margin: 0 }} />

                <Content
                    style={{
                        textAlign: "center",
                        flex: 1,
                        color: "#000",
                        backgroundColor: "#fff",
                        padding: 0,
                        overflow: "hidden",
                        display: "flex",
                        flexDirection: "column",
                    }}
                >
                    <div
                        style={{
                            width: "100%",
                            backgroundColor: "transparent",
                            // borderBottom: `1px solid ${token.colorBorderSecondary}`,
                            marginRight: "50px",
                        }}
                    >
                        <Segmented
                            options={options}
                            value={current}
                            onChange={onChange}
                            size="middle"
                            block
                            className="custom-segmented"
                        />
                    </div>

                    <div
                        style={{
                            flex: 1,
                            position: "relative",
                            overflow: "hidden",
                            minHeight: 0,
                            padding: "20px",
                            maxHeight: "78%",
                        }}
                    >
                        <AnimatePresence custom={direction}>
                            <motion.div
                                key={current}
                                custom={direction}
                                variants={variants}
                                initial="enter"
                                animate="center"
                                exit="exit"
                                transition={{
                                    duration: 0.3,
                                    ease: "easeInOut",
                                }}
                                style={{
                                    position: "absolute",
                                    width: "97%",
                                    height: "100%",
                                    overflow: "auto",
                                    userSelect: "text",
                                }}
                            >
                                {renderContent()}
                            </motion.div>
                        </AnimatePresence>
                    </div>
                </Content>
            </Layout>

            {/* 发布应用对话框 */}
            <AnimatePresence>
                {isDeployMounted && app && (
                    <motion.div
                        initial={{ opacity: 0, x: "100%" }}
                        animate={
                            isDeployVisible
                                ? { opacity: 1, x: 0 }
                                : { opacity: 0, x: "100%" }
                        }
                        exit={{ opacity: 0, x: "100%" }}
                        transition={{ duration: 0.3, ease: "easeInOut" }}
                        style={{
                            position: "fixed",
                            top: 0,
                            right: 0,
                            width: "100%",
                            height: "100%",
                            zIndex: 1000,
                        }}
                    >
                        <Deploy
                            ifShow={isDeployVisible}
                            setIfShow={(value) => {
                                if (!value) {
                                    setIsDeployVisible(false);
                                    const timer = setTimeout(
                                        () => setIsDeployMounted(false),
                                        300,
                                    );
                                    return () => clearTimeout(timer);
                                }
                                setShowDeploy(value);
                                return;
                            }}
                            App={app}
                            refreshAllApps={initAppInfo}
                        />
                    </motion.div>
                )}
            </AnimatePresence>
        </div>
    );
};

export default AppMorePage;